// const utilcpp = require('../../utils/cpp')
const utilslogin = require('../../utils/login_utils')

const app = getApp()

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}


Page({
  data: {
    devices: [],
    connected: false,
    blueView: false,
    chs: [],
    loginState: 0,
    deviceId:'',
    serviceId:'',
    loginCharacteristicId:'',
    canCharacteristicId: '',
    queryData:[],
    indexPower:'0',
    indexPowerLock:'0',
    indexScene:'0',
    indexSceneLock:'0',
    indexSpeed:'0',
    EBSvalue:'0',
    indexSpeedLock:'0',
    idlingSwitch:false,
    leftSwitch:false,
    rightSwitch:false,
    idleClose:false,
    timingView:false,
    timingValue:0,
    checkView:false,
    supprotCheck:false,
    chargeValue:0,
    cellMargin:100,
    cellIcon:10,
    united:false,
    carUrl:'',
    // userInfo:app.globalData.userInfo
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this.data.discoveryStarted) {
      return
    }
    this.data.discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      interval:200,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
        // 使用filter方法筛选出name属性以'GOWOW'开头的项
        const filteredDevices = this.data.devices.filter(device => device.name.startsWith('GOWOW'));
        this.setData({
          devices:filteredDevices
        })
        // console.log(filteredDevices);
        // console.log(this.data.devices);
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          // connected: true,
          united: true,
          name,
          deviceId,
        })
        console.log("蓝牙名称======" + this.data.name);
        wx.setStorageSync('bluetoothName', this.data.name);
        this.getBLEDeviceServices(deviceId)
        wx.showToast({
          title: "链接中",
          icon: 'loading',
          duration: 2000
        })
        setTimeout(() => {
          this.writeBLECharacteristicValue()
        }, 800);
        setTimeout(() => {
          this.setData({
            blueView: false,
          })
          wx.setStorageSync('blueView', this.data.blueView);
        }, 2000);
        
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  //断开链接
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log("获取蓝牙设备所有服务成功", res.services)
        let services_uuid="8EC34E30-A315-8E60-9FA8-838830DAEA49"
        // this.getBLEDeviceCharacteristics(deviceId, services_uuid)
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].uuid == services_uuid) {
            console.log( res.services[i]);
            // console.log("______");
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log(res);
        let login_uuid="8EC34E31-A315-8E60-9FA8-838830DAEA49"
        let can_uuid = "8EC34E32-A315-8E60-9FA8-838830DAEA49"
        this.data.deviceId = deviceId;
        this.data.serviceId = serviceId;
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if(item.uuid == login_uuid){
            console.log("获取登陆服务成功");
            this.data.loginCharacteristicId = item.uuid
          }else if (item.uuid == can_uuid) {
            this.data.canCharacteristicId = item.uuid;
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据，监听蓝牙低功耗设备的特征值变化事件
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (characteristic.characteristicId == this.data.loginCharacteristicId) {
        if (this.data.loginState == 1) {
          console.log("获取登陆密码");
          this.getSN(characteristic.value)
        }else if (this.data.loginState == 2) {
          console.log("success, ------------------")
          this.cell()//读电池
          this.inquire()//读动力、场景、速度、EBS
          this.readClose()//读闲置定时关机
          this.readSupprot()//读是否支持修改充电功率
        }
        console.log(characteristic.value);
      }else if(characteristic.characteristicId == this.data.canCharacteristicId){
        let characteristicValue = ab2hex(characteristic.value).match(/.{2}/g)
        let verifyValue = characteristicValue.slice(1,5).join("")
        console.log(verifyValue);
        if(verifyValue == "14090702" || verifyValue == "17093f02"){//读取电量得到的回复
          console.log("读取电量得到的回复",characteristicValue);
          let gointValue = characteristicValue[12] + characteristicValue[11]
          // console.log("拼接的值",gointValue);
          let margin = Math.floor(parseInt(gointValue, 16) / 384) 
          if (margin > 100) {
            margin = 100
          }
          console.log("剩余电量",margin);
          this.setData({
            cellMargin: margin,
            cellIcon:Math.round(margin / 10)
          })
        }else if(verifyValue == "14060701"){//读取动力、场景、速度、EBS得到的回复
          console.log("读取动力、场景、速度、EBS得到的回复",characteristicValue);
          //["73", "14", "06", "07", "01", "14", "02", "50", "86", "08", "00", "5a", "00", "17"]
          let queryPower = characteristicValue[5]
          this.setData({
            indexPower:queryPower[0],
            indexScene:queryPower[1],
            indexSpeed:characteristicValue[6],
            EBSvalue:parseInt(characteristicValue[11], 16),
            queryData:characteristicValue
          })
          console.log(this.data.EBSvalue);
        }else if(verifyValue == "14060703"){//读取闲置定时关机得到的回复
          console.log("读取闲置定时关机得到的回复",characteristicValue);
          let readValue = characteristicValue[10] + characteristicValue[9]
          if(readValue == "ffff"){
            this.setData({
              timingValue:0
            })
          }else{
            this.setData({
              timingValue:parseInt(readValue, 16)/60
            })
          }
          if(this.data.timingValue){
            this.setData({
              idleClose:true
            })
          }
          console.log("初始化读取闲置定时关机时间"+this.data.timingValue);
        }else if(verifyValue == "14080702"){//读取是否支持修改充电功率得到的回复
          console.log("读取是否支持修改充电功率得到的回复",characteristicValue);
          if((`0x${characteristicValue[5]}` & '0x08') == '0x08'){
            console.log('支持修改充电功率');
            this.setData({
              supprotCheck:true
            })
            setTimeout(() => {
              this.readCharge()//读充电功率 
            }, 500);        
          }else{
            console.log('不支持修改充电功率');
          }
        }else if(verifyValue == "14800702" || verifyValue == "17803f02"){//读取充电功率得到的回复
          console.log("读取充电功率得到的回复",characteristicValue);
          let readChargeValue = characteristicValue[6] + characteristicValue[5]
          this.setData({
            chargeValue:parseInt(readChargeValue, 16)
          })
        }
      }
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // console.log(data);
      // console.log(this.data.chs);
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  //获取登录密码
  getSN(snValue){
    this.getvalue = ab2hex(snValue).match(/.{2}/g)
    // console.log("得到的数据，再转字符串，转数组", this.getvalue);
    //将转换的ASCII码字符
    var ecuSn = utilslogin.login(this.getvalue)
    // console.log("ASCII码字符：result=" + ecuSn + typeof(ecuSn));
    //将转换的ASCII码字符和用户id发给后端接口得到SN密钥
    var _this = this;
    wx.request({
      url: 'https://api.gowow.cn/factory/ecu/code',
      data: {
        "ecuSn": ecuSn,
        "riderId": app.globalData.userInfo.id
      },
      method:'POST',
      success (res) {
        //拿到SN密钥，加工成登录密码outPassword
        var outPassword = utilslogin.request(ecuSn, res.data.data)
        console.log("outPassword=" + outPassword);
        //求和、拼接
        var sum = (utilslogin.sum(outPassword) + 0x73 + 0x81 + 0x02 + 0x08) & 0xff
        console.log("sum=" + sum);
        var bufferArr = new Uint8Array(14);
        bufferArr[0] = 0x73;
        bufferArr[1] = 0x81;
        bufferArr[2] = 0x02;
        bufferArr[3] = 0x08;
        for(var i = 0; i < outPassword.length; i++) {
          bufferArr[4 + i] = outPassword[i];
        }
        bufferArr[12] = sum;
        bufferArr[13] = 0x17;
        console.log(utilslogin.uint8Array(bufferArr))
        let buffer = bufferArr.buffer;
        // console.log(buffer);
        // console.log(_this.data.deviceId);
        // console.log(_this.data.serviceId);
        // console.log(_this.data.loginCharacteristicId);
        _this.data.loginState = 2;
        wx.writeBLECharacteristicValue({
          deviceId: _this.data.deviceId,
          serviceId: _this.data.serviceId,
          characteristicId: _this.data.loginCharacteristicId,
          value: buffer,
        })
        // console.log(snValue);
      }
    }) 
  },
  //请求登陆的方法
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new Uint8Array([0x73, 0x81, 0x01, 0x00, 0xf5, 0x17]).buffer;
    this.data.loginState = 1;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.loginCharacteristicId,
      value: buffer,
    })
  },
  //自定义动力模式功能未开放
  unopen(){
    wx.showToast({
      title: '功能未开放',
      icon: 'error'
    })
  },
  //激活动力开关锁类名
  powerLock: function(event) {
    this.setData({
      indexPowerLock:event.currentTarget.dataset.index
    })
    if(this.data.indexPowerLock == '1'){
      wx.showToast({
        title: '锁定动力模式',
        duration: 700,
        icon: 'error',
      });
    }else{
      wx.showToast({
        title: '动力模式解锁',
        duration: 700
      });
    }
    this.controlCar(event)
  },
  //激活动力模式类名
  activePower: function(event) {
    if(this.data.indexPowerLock == '0'){
      this.setData({
        indexPower:event.currentTarget.dataset.index
      })
      this.controlCar(event)
    }else{
      wx.showToast({
        title: '请解锁动力模式',
        icon: 'error',
      })
    }
  },
   //激活场景开关锁类名
  sceneLock: function(event) {
    this.setData({
      indexSceneLock:event.currentTarget.dataset.index
    })
    if(this.data.indexSceneLock == '1'){
      wx.showToast({
        title: '锁定场景模式',
        duration: 700,
        icon: 'error',
      });
    }else{
      wx.showToast({
        title: '场景模式解锁',
        duration: 700
      });
    }
    this.controlCar(event)
  },
  //激活场景模式类名
  activeScene: function(event) {
    if(this.data.indexSceneLock == '0'){
      this.setData({
        indexScene:event.currentTarget.dataset.index
      })
      this.controlCar(event)
    }else{
      wx.showToast({
        title: '请解锁场景模式',
        icon: 'error',
      })
    }
  },
  //激活速度模式类名
  activeSpeed: function(event) {
    this.setData({
      indexSpeed:event.currentTarget.dataset.index
    })
    this.controlCar(event)
  },
  //闲置定时关机滑块叉号方法
  outBtnTiming() {
    this.setData({
      timingView : false
    })
  },
  //充电功率滑块叉号方法
  outBtnTiming() {
    this.setData({
      checkView : false
    })
  },
  //怠速模式开关
  idling: function(event) {
    this.setData({
      idlingSwitch:!this.data.idlingSwitch
    })
    if (this.data.idlingSwitch) {
      console.log(event.currentTarget.dataset.param);
      this.controlCar(event)
    }else{
      console.log(event.currentTarget.dataset.param);
      this.controlCar(event)
    }
  },
  //电子左刹车开关
  leftBrake: function(event) {
    this.setData({
      leftSwitch:!this.data.leftSwitch
    })
    if (this.data.leftSwitch) {
      console.log(event.currentTarget.dataset.param);
      this.controlCar(event)
    }else{
      console.log(event.currentTarget.dataset.param);
      this.controlCar(event)
    }
  },
  //电子右刹车开关
  ringhtBrake: function(event) {
    this.setData({
      rightSwitch:!this.data.rightSwitch
    })
    if (this.data.rightSwitch) {
      console.log(event.currentTarget.dataset.param);
      this.controlCar(event)
    }else{
      console.log(event.currentTarget.dataset.param);
      this.controlCar(event)
    }
  },
  //读取闲置定时关机
  readClose(){
    var cellArr = new Uint8Array(14);
    cellArr[0] = 0x73;
    cellArr[1] = 0x13;
    cellArr[2] = 0x71;
    cellArr[3] = 0x03;
    cellArr[4] = 0x07;
    cellArr[5] = 0x06;
    cellArr[6] = 0x01;
    for(var i = 0; i < 6; i++) {
      cellArr[7 + i] = 0x00;
    }
    cellArr[13] = 0x17;
    console.log("读取闲置定时关机方法运行");
    let buffer = cellArr.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  //闲置定时关机
  timingClose: function(event) {
    this.setData({
      idleClose:!this.data.idleClose
    })
    if (this.data.idleClose) {
      this.setData({
        timingView : true
      })
      // this.controlCar(event)
    }else{
      // this.controlCar(event)
    }
  },
  //定时加
  timingAdd(){
    this.setData({
      timingValue:this.data.timingValue+1
    })
  },
  //定时减
  timingSubtract(){
    this.setData({
      timingValue:this.data.timingValue-1
    })
  },
  //滑动定时
  timingChange: function(e)  {
    this.setData({
      timingValue:e.detail.value
    })
    console.log(`timingslider发生change事件，携带值为`, e.detail.value)
  },
  //修改滑轮定时
  alterTiming(){
    this.setData({
      timingView : true
    })
  },
  //确认修改闲置定时
  yesTiming(){
    this.setData({
      timingView : false
    })
    let bufferone = new Uint8Array([0x73,0x11,0x04,0x03,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x17]).buffer;
          /*读命令：0x7313710307060100000000000017
            读结果：<73140607 03e90894 0a040b00 0017>
            修改前：e908940a 040b 0000
            修改后：e908940a 0000 0000
            发送修改允许命令：<73110403 07070000 00000000 0017>
            返送修改命令：<73110603 07e90894 0a000000 0017>*/
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: bufferone,
    })
    let alterValue = (this.data.timingValue * 60).toString(16).padStart(4, '0');
    let alterArr = [0x73,0x11,0x06,0x03,0x07,0xe9,0x08,0x94,0x0a,`0x${alterValue.slice(2)}`,`0x${alterValue.slice(0,2)}`,`0x00`,`0x00`,0x17]
    let buffertwo = new Uint8Array(alterArr).buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffertwo,
    })
  },
  //读取是否支持修改充电功率
  readSupprot(){
    var cellArr = new Uint8Array(14);
    cellArr[0] = 0x73;
    cellArr[1] = 0x13;
    cellArr[2] = 0x71;
    cellArr[3] = 0x02;
    cellArr[4] = 0x07;
    cellArr[5] = 0x08;
    cellArr[6] = 0x01;
    for(var i = 0; i < 6; i++) {
      cellArr[7 + i] = 0x00;
    }
    cellArr[13] = 0x17;
    console.log("读取是否支持修改充电功率方法运行");
    let buffer = cellArr.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  //读取充电功率
  readCharge(){
    var cellArr = new Uint8Array(14);
    cellArr[0] = 0x73;
    cellArr[1] = 0x13;
    cellArr[2] = 0x71;
    cellArr[3] = 0x02;
    cellArr[4] = 0x07;
    cellArr[5] = 0x80;
    cellArr[6] = 0x01;
    for(var i = 0; i < 6; i++) {
      cellArr[7 + i] = 0x00;
    }
    cellArr[13] = 0x17;
    console.log("读取充电功率方法运行");
    let buffer = cellArr.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  //查看充电功率
  chargeCheck: function(event) {
    if(this.data.supprotCheck){
      this.readCharge()//读充电功率  
      this.setData({
        checkView : true
      })
    }else{
      wx.showToast({
        title: '该车型不支持',
        icon:'error'
      })
    }
  },
  //滑动调整充电功率
  chargeChange: function(e)  {
    this.setData({
      chargeValue:e.detail.value
    })
  },
  
            /*
            查询是否支持充电功率设定 0x7313710207080100000000000017
            查询结果：<73140807 02 0e0017 00e803b6 0317>
            判断第一个字节： 0x0e & 0x08 == 0x08  表示支持
          
            读取充电功率 0x7313710207800100000000000017
            14800702  或  17803F02
            <7317803f 027a0364 00000000 0017>
            结果：7a03 读数：0x037a   (890)
            0x64 = 100 (表示充电充到 100%)
          
            写充电功率，修改为  1000 kw.h
            0000640000000000  替换前四位 e80364 00000000 00
            或：<73118002 07e80364 00000000 0017>
            */ 
  //充电功率确认
  yesCharge(){
    this.setData({
      checkView : false
    })
    let alterValue = this.data.chargeValue.toString(16).padStart(4, '0');
    let alterArr = [0x73,0x11,0x80,0x02,0x07,`0x${alterValue.slice(2)}`,`0x${alterValue.slice(0,2)}`,0x64,`0x00`,`0x00`,`0x00`,`0x00`,`0x00`,0x17]
    console.log(alterArr);
    let buffertwo = new Uint8Array(alterArr).buffer;
    console.log(buffertwo);
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffertwo,
    })
  },
  //读取电池余量
  cell(){
    var cellArr = new Uint8Array(14);
    cellArr[0] = 0x73;
    cellArr[1] = 0x13;
    cellArr[2] = 0x71;
    cellArr[3] = 0x02;
    cellArr[4] = 0x07;
    cellArr[5] = 0x09;
    cellArr[6] = 0x01;
    for(var i = 0; i < 6; i++) {
      cellArr[7 + i] = 0x00;
    }
    cellArr[13] = 0x17;
    console.log("读取电池余量方法运行");
    // console.log(ab2hex(cellArr).match(/.{2}/g));
    let buffer = cellArr.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  //读取动力、场景、速度、EBS
  inquire(){
    var cellArr = new Uint8Array(14);
    cellArr[0] = 0x73;
    cellArr[1] = 0x13;
    cellArr[2] = 0x71;
    cellArr[3] = 0x01;
    cellArr[4] = 0x07;
    cellArr[5] = 0x06;
    cellArr[6] = 0x01;
    for(var i = 0; i < 6; i++) {
      cellArr[7 + i] = 0x00;
    }
    cellArr[13] = 0x17;
    console.log("读取动力、场景、速度、EBS方法运行");
    let buffer = cellArr.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  //调整EBS
  sliderChange: function(e)  {
    console.log(`slider发生change事件，携带值为`, e.detail.value)
    // this.setData({
    //   EBSvalue:e.detail.value
    // })
    //["73", "14", "06", "07", "01", "14", "02", "50", "86", "08", "00", "00", "00", "17"]
    var controlArr = new Uint8Array(14);
    controlArr[0] = 0x73;
    controlArr[1] = 0x11;
    controlArr[2] = 0x06;
    controlArr[3] = 0x01;
    controlArr[4] = 0x07;
    controlArr[5] = `0x${this.data.indexPower}${this.data.indexScene}`;
    controlArr[6] = `0x${this.data.indexSpeed}`;
    controlArr[7] = 0x00;
    controlArr[8] = 0x00;
    controlArr[9] = 0x00;
    controlArr[10] = 0x00;
    controlArr[11] = `0x${e.detail.value.toString(16)}`;
    controlArr[12] = 0x00;
    controlArr[13] = 0x17;
    console.log(controlArr[8], typeof(controlArr[8]));
    console.log(controlArr[11], typeof(controlArr[11]));
    let buffer = controlArr.buffer;
    console.log(buffer);
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  // 向蓝牙设备发送控制命令
  controlCar: function(event)  {
    // 获取传递的参数值
    var param = event.currentTarget.dataset.param;
    // console.log(param , typeof(param)); 
    var controlArr = new Uint8Array(14);
    controlArr[0] = 0x73;
    controlArr[1] = 0x11;
    controlArr[2] = 0x04;
    controlArr[3] = 0x01;
    controlArr[4] = 0x07;
    controlArr[5] = param;
    for(var i = 0; i < 7; i++) {
      controlArr[6 + i] = 0x00;
    }
    controlArr[13] = 0x17;
    let buffer = controlArr.buffer;
    // console.log(buffer);
    // console.log(this.data.deviceId);
    // console.log(this.data.serviceId);
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.canCharacteristicId,
      value: buffer,
    })
  },
  //结束流程
  closeBluetoothAdapter() {
    const that = this;
    wx.showModal({
      title: '操作确认',
      content: `您要确定断开蓝牙链接吗？`,
      success (res) {
        if (res.confirm) {
          wx.closeBluetoothAdapter()
          that.data.discoveryStarted = false
          that.setData({
            blueView: true,
            devices:[]
          })
          wx.setStorageSync('blueView', that.data.blueView);
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },
  onLoad (option) {
    // let exs = '0e'
    // console.log(('0x0e' & '0x08') == '0x08');
    this.openBluetoothAdapter()
    setInterval(() => {
      this.inquire()
    }, 5000);
    // console.log(option.token)
    wx.request({
      url: 'https://api.gowow.cn/user/profile',
      method:'GET',
      header:{
        Authorization: option.token
      },
      success (res) {
        //将获取骑的数据存储到全局变量中
        app.globalData.userInfo = res.data.data;
        // console.log("在本页面直接赋值给this.userInfo是不成功的,用app.globalData.userInfo即可获取骑手数据" + this.userInfo);
        console.log(app.globalData.userInfo);
      }
    })
    /*
    获取车辆列表
    */
    const that = this;
    wx.request({
      url: 'https://api.gowow.cn/moto/my',
      method:'GET',
      header:{
        Authorization: option.token
      },
      success (res) {
        for (let i = 0; i < res.data.data.length; i++) {
          if(res.data.data[i].isDefault){
            that.setData({
              carUrl : res.data.data[i].picture
            })
          }
        }
        // that.setData({
        //   mycarList : res.data.data
        // })
        // console.log("home页面车辆列表");
        // console.log(that.data.mycarList);
        console.log(that.data.carUrl);
      }
    })
  }
})
